package com.mrx.xfriendship.telnet.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * @author Mr.X
 * @since 2023-01-23 11:46
 */
public class TelnetServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final Charset charset = Charset.forName("GBK");

    private static final StringDecoder DECODER = new StringDecoder(charset);

    private static final StringEncoder ENCODER = new StringEncoder(charset);

    private final TelnetServerHandler serverHandler;

    public TelnetServerInitializer(TelnetServerHandler serverHandler) {
        this.serverHandler = serverHandler;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        // Add the text line codec combination first,
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        // the encoder and decoder are static as these are sharable
        pipeline.addLast(DECODER);
        pipeline.addLast(ENCODER);
        // and then business logic.
        pipeline.addLast(serverHandler);
    }

}
